package cn.bigway.app.weavingdesigner.weaving;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

import cn.bigway.app.weavingdesigner.image.WdImage;
import cn.bigway.app.weavingdesigner.log.WdLog;
import cn.bigway.app.weavingdesigner.needle.WdNeedleBox;
import cn.bigway.app.weavingdesigner.operator.WdDocOperationManager;

public class WdDocPanel extends JPanel {

	private static final long serialVersionUID = -4251674873220740964L;

	private static final double MIN_ZOOM = 0.1;

	private double zoom;
	private WdNeedleBox needleBox;
	private WdImage foundationImage, presentImage, operationImage;

	private WdWeavingDoc weavingDoc;
	private WdDocOperationManager opManager;

	WdDocPanel(WdWeavingDoc weavingDoc) {
		this.zoom = 1.0;
		this.weavingDoc = weavingDoc;
		WdWeavingDocInitData data = this.weavingDoc.getInitData();

		this.needleBox = new WdNeedleBox(data.getNeedleCount());

		setBackground(this.needleBox.getBackgroundColor());

		this.foundationImage = WdImage
				.create(data.getWidth(), data.getHeight());
		this.presentImage = WdImage.create(data.getWidth(), data.getHeight());
		this.operationImage = WdImage.create(data.getWidth(), data.getHeight());

		this.opManager = new WdDocOperationManager();
		setFocusable(true);
		addKeyListener(this.opManager);
		addMouseListener(this.opManager);
		addMouseWheelListener(this.opManager);
		addMouseMotionListener(this.opManager);
	}

	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D grp = (Graphics2D) g;
		grp.scale(this.zoom, this.zoom);
		grp.drawImage(this.presentImage, 0, 0, this);
		grp.drawImage(this.operationImage, 0, 0, this);
		grp.drawLine(0, 0, 100, 100);
		grp.dispose();
		WdLog.debug("paintComponent");
	}

	@Override
	public Dimension getPreferredSize() {
		return new Dimension(
				(int) (this.presentImage.getWidth(this) + (this.presentImage
						.getWidth(this) * (this.zoom - 1))),
				(int) (this.presentImage.getHeight(this) + (this.presentImage
						.getHeight(this) * (this.zoom - 1))));
	}

	public void setZoom(double value) {
		this.zoom = value;
		if (this.zoom < MIN_ZOOM) {
			this.zoom = MIN_ZOOM;
		}
		this.weavingDoc.adjustLayout();
	}

	public double getZoom() {
		return this.zoom;
	}
}